//
//  HomeViewController.m
//  financial
//
//  Created by Apple on 2017/9/21.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "HomeViewController.h"
#import "MessageBaseViewController.h"
#import "SearchBaseViewController.h"
#import "HomeShareViewController.h"
#import "HomeWebViewController.h"

#import "HomeModel.h"
#import "HomeMoreBtnCell.h"
#import "HomeStyleOneCell.h"
#import "HomeStyleTwoCell.h"
#import "HomeStyleThreeCell.h"
#import "JAScrollView.h"

//#import "VideoDetailViewController.h"
#import "AnalysisListViewController.h"
#import "RKNotificationHub.h"
#import "ActivityListViewController.h"
//#import "TransactViewController.h"
#import "FinancialProductsCell.h"
#import "CreateAccountViewController.h"
#import "LearnListViewController.h"

static NSString * HMCellID = @"HomeMoreBtnCellID";
static NSString * HoneCellID = @"HomeStyleOneCell";
static NSString * HtwoCellID = @"HomeStyleTwoCell";
static NSString * HthreeCellID = @"HomeStyleThreeCell";

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UIButton         * leftBtn;
@property (nonatomic,strong) UIButton         * rightBtn;
@property (nonatomic,strong) UITableView      * tableView;
@property (nonatomic,strong) NSMutableArray   * dataArray;
@property (nonatomic,strong) JAScrollView     * scrollView;
@property (nonatomic,strong) RKNotificationHub* hub;
@property (nonatomic,strong) NSMutableArray   * imageArray;
@property (nonatomic,strong) NSMutableArray   * imageDataArray;
@end

@implementation HomeViewController

#pragma mark --- 请求首页消息数
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self checkMsg];
}

- (void)checkMsg {
    WeakSelf
    [HttpRequest postWithURLString:HOST(@"app/message/unReadNum") parameters:nil showProgressHud:NO success:^(NSDictionary * _Nullable responseObject) {
        if ([responseObject[@"data"][@"unReadNum"] integerValue] > 0) {
            [weakSelf.hub hideCount];
            [weakSelf.hub showHot];
        }else{
            [weakSelf.hub hiddenHot];
        }
    } failure:^(NSError * _Nullable error) {
        
    } login:^(BOOL isLogin) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setCusNav];
    [self setCusTable];
    [self reloadCusData];
}
- (UIButton *)leftBtn {
    
    if (!_leftBtn) {
        _leftBtn = [[UIButton alloc] init];
        [_leftBtn setImage:[UIImage imageNamed:@"home_msg"] forState:UIControlStateNormal];
        [_leftBtn addTarget:self action:@selector(clickBarLeftAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftBtn;
}
- (UIButton *)rightBtn {
    
    if (!_rightBtn) {
        _rightBtn = [[UIButton alloc] init];
        [_rightBtn setImage:[UIImage imageNamed:@"home_search"] forState:UIControlStateNormal];
        [_rightBtn addTarget:self action:@selector(clickBarRightAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}
- (void)clickBarLeftAction:(UIButton *)sender {
    
    MessageBaseViewController * mv = [[MessageBaseViewController alloc] init];
    mv.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mv animated:YES];
}

- (void)clickBarRightAction:(UIButton *)sender {
    
    SearchBaseViewController * sc = [[SearchBaseViewController alloc] init];
    sc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:sc animated:YES];
}

- (void)setCusNav
{
    [self setHideBackBtn:YES];
    [self.titleL setText:@"香河党建"];
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    
    [self.barView addSubview:self.leftBtn];
    [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.size.mas_offset(CGSizeMake(25, 25));
        make.centerY.mas_equalTo(self.barView);
    }];
    [self.view layoutIfNeeded];
    self.hub = [[RKNotificationHub alloc]initWithView:self.leftBtn];
    [self.hub moveCircleByX:-10 Y:10];

    [self.barView addSubview:self.rightBtn];
    [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.size.mas_offset(CGSizeMake(25, 25));
        make.centerY.mas_equalTo(self.barView);
    }];
}

#pragma mark --- 请求首页数据源
- (void)networking {
    
    WeakSelf
    [HttpRequest postWithURLString:HOST(@"app/home") parameters:nil showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
        [weakSelf.tableView.mj_header endRefreshing];
        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
            NSLog(@"%@",responseObject);
            for (NSDictionary * dict in responseObject[@"data"]) {
                if (!dict) {
                    weakSelf.tableView.hidden = YES;
                    weakSelf.NoDataView.hidden = NO;
                }else{
                    weakSelf.tableView.hidden = NO;
                    weakSelf.NoDataView.hidden = YES;
                }
                if ([dict[@"moduleType"] isEqualToString:@"slide"]) {
                    for (NSDictionary *imgDic in dict[@"content"]) {
                        [weakSelf.imageArray addObject:imgDic[@"image"][@"path"]];
                        [weakSelf.imageDataArray addObject:imgDic];
                    }
                }else{
                    HomeModel *model = [[HomeModel alloc] initWithDic:dict];
                    [weakSelf.dataArray addObject:model];
                }
            }
            [weakSelf.tableView reloadData];
        }
    } failure:^(NSError * _Nullable error) {
        [weakSelf.tableView.mj_header endRefreshing];
        weakSelf.tableView.hidden = YES;
        weakSelf.NoDataView.hidden = NO;
    }login:^(BOOL isLogin) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf ShowLoginView];
        });
    }];
}
- (void)ShowLoginView
{
    HFLoginView * logView = [HFLoginView shareInit];
    [logView show];
    WeakSelf
    logView.clickPushBlock = ^(NSInteger index) {
        if (index == 0) {
            [weakSelf PushRigest];
        }else{
            [weakSelf PushLogin];
        }
    };
}
- (void)PushRigest
{
    RegisterViewController * rc = [[RegisterViewController alloc] init];
    rc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:rc animated:YES];
}
- (void)PushLogin
{
    LoginViewController * lgvc = [[LoginViewController alloc] init];
    lgvc.myClass = NSStringFromClass([self class]);
    WeakSelf
    lgvc.LoginSuccessBlock = ^{
        [weakSelf reloadCusData];
    };
    lgvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:lgvc animated:YES];
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)setCusTable
{
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.barView.mas_bottom).offset(0);
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIColorRGB(0xeeeeee);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadCusData)];
}
- (void)reloadCusData
{
    [self.dataArray removeAllObjects];
    [self.imageDataArray removeAllObjects];
    [self.imageArray removeAllObjects];
    [self networking];
}
- (NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}
- (NSMutableArray *)imageDataArray
{
    if (!_imageDataArray) {
        _imageDataArray = [NSMutableArray array];
    }
    return _imageDataArray;
}

- (JAScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[JAScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 210 * SizeWidth)];
    }
    return _scrollView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[HomeMoreBtnCell class] forCellReuseIdentifier:HMCellID];
        [_tableView registerClass:[HomeStyleOneCell class] forCellReuseIdentifier:HoneCellID];
        [_tableView registerClass:[HomeStyleTwoCell class] forCellReuseIdentifier:HtwoCellID];
        [_tableView registerClass:[HomeStyleThreeCell class] forCellReuseIdentifier:HthreeCellID];
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HomeModel *model;
    if (self.dataArray.count > 0) {
        model = self.dataArray[section];
    }
    
    if ([model.moduleType isEqualToString:@"icon"]) {
        return 1;
    }else if ([model.moduleType isEqualToString:@"customer"] && [model.title isEqualToString:@"金融资讯"]) {
        return [model.content count];
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeModel *model;
    if (self.dataArray.count > 0) {
        model = self.dataArray[indexPath.section];
    }
    if ([model.moduleType isEqualToString:@"icon"]) {
        return 230.f;
    }
    if ([model.moduleType isEqualToString:@"customer"]&& [model.title isEqualToString:@"金融资讯"]) {
        switch ([model.style integerValue]) {
            case 1:
            {
                NSInteger i = [[model.content firstObject] count];
                if (i % 2 > 0) {
                    i = i + 1;
                }
                return 95 * SizeWidth * i / 2 + 8 + 35 * i / 2;
            }
                break;
            case 2:
            {
                NSInteger i = [[model.content firstObject] count];
                if (i % 3 > 0) {
                    i = i + 2;
                }
                CGFloat W = (SCREENWIDTH - 90) / 3;
                CGFloat H = W * 1.4;
                if ([[model.content firstObject] count] > 3) {
                    return H * i / 3 + 34 * i / 3 + 10;
                }else{
                    return H + 44;
                }
            }
                break;
            case 3:
            {
                return 105.f;
            }
                break;
            default:
                break;
        }
    }
    return 0.0f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WeakSelf
    HomeModel *model;
    if (self.dataArray.count > 0) {
        model = self.dataArray[indexPath.section];
    }
    HomeMoreBtnCell * HmCell = [[HomeMoreBtnCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HMCellID];
    HomeStyleOneCell * HoneCell = [[HomeStyleOneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HoneCellID];
    HomeStyleTwoCell * HtwoCell = [[HomeStyleTwoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HtwoCellID];
    HomeStyleThreeCell * HthreeCell = [[HomeStyleThreeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HthreeCellID];

    //菜单
    if ([model.moduleType isEqualToString:@"icon"]) {
        [HmCell setDataWithModel:model];
        HmCell.ButtonClickBlock = ^(NSInteger index) {
            [weakSelf PushButtonActionModel:model index:index];
        };
        return HmCell;
    }

    //列表
    if ([model.moduleType isEqualToString:@"customer"]&& [model.title isEqualToString:@"金融资讯"]) {
        switch ([model.style integerValue]) {
            case 1:
            {
                HoneCell.selectionStyle = UITableViewCellSelectionStyleNone;
                [HoneCell setDataWithModel:model];
                HoneCell.clickCellImgBlock = ^(NSInteger index) {
                    HomeModel * pushModel = self.dataArray[indexPath.section];
                    NSDictionary * dict = pushModel.content[0][index];
                    [weakSelf pushType:[dict[@"type"] integerValue] value:dict[@"value"] dict:dict];
                };
                return HoneCell;
            }
                break;
            case 2:
            {
                HtwoCell.selectionStyle = UITableViewCellSelectionStyleNone;
                [HtwoCell setDataWithModel:model];
                HtwoCell.clickCellImgBlock = ^(NSInteger index) {
                    HomeModel * pushModel = self.dataArray[indexPath.section];
                    NSDictionary * dict = pushModel.content[0][index];
                    [weakSelf pushType:[dict[@"type"] integerValue] value:dict[@"value"] dict:dict];
                };
                return HtwoCell;
            }
                break;
            case 3:
            {
                [HthreeCell setDataWithDict:model.content[indexPath.row]];
                return HthreeCell;
            }
                break;
            default:
                break;
        }
    }
    return HmCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 210 * SizeWidth;
    }
    return 0.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        WeakSelf
        self.scrollView.imagesArray = self.imageArray;
        [self.scrollView initView];
        self.scrollView.block = ^(NSInteger index){
            NSDictionary * dict = weakSelf.imageDataArray[index];
            [weakSelf pushType:[dict[@"type"] integerValue] value:dict[@"value"] dict:dict];
        };
        return self.scrollView;
    }
    return nil;
}

#pragma mark - 点击图片
- (void)PushButtonActionModel:(HomeModel *)model index:(NSInteger)index
{
    switch (index) {
        case 0:
        {
//            ActivityListViewController * ac = [[ActivityListViewController alloc] init];
//            ac.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:ac animated:YES];
        }
            break;
        case 1:
        {
            ActivityListViewController * ac = [[ActivityListViewController alloc] init];
            ac.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:ac animated:YES];
        }
            break;
        case 2:
            
            break;
        case 3:
            
            break;
        case 4:
            
            break;
        case 5:
            
            break;

        default:
            break;
    }

    
}

#pragma mark - 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    HomeModel *model = self.dataArray[indexPath.section];
    
    NSDictionary * contentDict = model.content[indexPath.row];
    [self pushType:[contentDict[@"type"] integerValue] value:contentDict[@"value"] dict:contentDict];
    
}

- (void)pushType:(NSInteger)type value:(id)value dict:(NSDictionary *)dict
{
    WeakSelf
    switch (type) {
        case 1://打开网页
        {
            HomeShareViewController * hc = [[HomeShareViewController alloc] init];
            hc.hidesBottomBarWhenPushed = YES;
            hc.cusTitle = dict[@"title"];
            hc.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?token=%@",value,[HFUser getSaveToken]]];
            [self.navigationController pushViewController:hc animated:YES];
        }
            break;
        case 10://分析列表
        {
            AnalysisListViewController * ac = [[AnalysisListViewController alloc] init];
            ac.hidesBottomBarWhenPushed = YES;
            ac.value = value;
            ac.cusTitle = dict[@"title"];
            [self.navigationController pushViewController:ac animated:YES];
        }
            break;
        case 11://分析详情
        {
            HomeWebViewController * hc = [[HomeWebViewController alloc] init];
            hc.hidesBottomBarWhenPushed = YES;
            hc.cusTitle = dict[@"title"];
            hc.imageUrl = dict[@"image"][@"path"];
            hc.shareUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?id=%@",OS,@"/wap/app/analysis/info",value]];
            hc.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?token=%@&id=%@&pc=1",OS,@"/wap/app/analysis/info",[HFUser getSaveToken],value]];
            [self.navigationController pushViewController:hc animated:YES];
        }
            break;
        case 20://课程详情
        {
            NSString * vid = [NSString stringWithFormat:@"%@",dict[@"extra"][@"videoId"]];
            NSString * sid = [NSString stringWithFormat:@"%@",dict[@"value"]];
            if (vid.length > 0) {
                [HttpRequest postWithURLString:HOST(@"app/section/play/auth") parameters:@{@"sid":sid,@"videoId":vid,@"vno":VERSION} showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
                    if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
//                        VideoDetailViewController * vc = [[VideoDetailViewController alloc] init];
//                        vc.vid = vid;
//                        vc.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?id=%@&token=%@&pc=1",OS,@"/wap/app/course/info",sid,[HFUser getSaveToken]]];
//                        vc.path_auth = responseObject[@"data"][@"playAuth"];
//                        [weakSelf presentViewController:vc animated:YES completion:^{
//
//                        }];
                    }
                } failure:^(NSError * _Nullable error) {
                    NSLog(@"%@",error);
                } login:^(BOOL isLogin) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf ShowLoginView];
                    });
                }];
            }
        }
            break;
        case 21://课程列表
        {
//            KnowDetailViewController * kc = [[KnowDetailViewController alloc] init];
//            kc.hidesBottomBarWhenPushed = YES;
//            kc.isCouser = YES;
//            kc.couserId = [NSString stringWithFormat:@"%@",value];
//            [self.navigationController pushViewController:kc animated:YES];
        }
            break;
        case 22://自定义课程列表
        {
//            CustomCourseViewController * cv = [[CustomCourseViewController alloc] init];
//            cv.hidesBottomBarWhenPushed = YES;
//            cv.courseID = [NSString stringWithFormat:@"%@",value];
//            cv.cusTitle = dict[@"title"];
//            [self.navigationController pushViewController:cv animated:YES];
        }
            break;
        case 30://在线学习
        {
            ActivityListViewController * ac = [[ActivityListViewController alloc] init];
            ac.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:ac animated:YES];
        }
            break;
            
            
            
            
            
        case 31://学股堂
        {
            LearnListViewController * lc = [[LearnListViewController alloc] init];
            lc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:lc animated:YES];
        }
            break;
        case 32://模拟炒股
        {
//            TransactViewController * tc = [[TransactViewController alloc] init];
//            tc.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:tc animated:YES];
        }
            break;
        case 40://开户
        {
            CreateAccountViewController * cc = [[CreateAccountViewController alloc] init];
            cc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:cc animated:YES];
        }
            break;
        default:
            break;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
